<template>
  <div class='container'>
    <!-- 弹窗 -->
        <el-dialog :title="dialogTitle" :visible="showdialog" width="400px" @close="cancel">
          <el-form :model="newForm" :rules="rules" ref="newForm">
            <el-form-item label="学科名称" prop="subjectName">
              <el-input v-model="newForm.subjectName" placeholder="请输入学科名称" style="width:280px"/>
            </el-form-item>
            <el-form-item label="前台是否显示" style="margin-left:10px">
              <el-switch v-model="newForm.isFrontDisplay" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
            </el-form-item>
          </el-form>
          <el-row type="flex" justify="end">
              <el-button size="middle" @click="cancel">取消</el-button>
              <el-button type="primary" size="middle" @click="okBtn">确定</el-button>
          </el-row>
        </el-dialog>
  </div>
</template>

<script>
import { add, update, detail } from '@/api/hmmm/subjects'
export default {
  props: {
    showdialog: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    dialogTitle () {
      return this.newForm.id ? '编辑学科' : '新增学科'
    }
  },
  data () {
    return {
      newForm: { // 弹窗表单
        subjectName: '',
        isFrontDisplay: true
      },
      rules: {
        subjectName: [{ required: true, message: '请输入学科名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 新增学科&&修改学科提交
    okBtn () {
      this.$refs.newForm.validate(async valid => {
        if (valid) { // 非空校验
          this.newForm.isFrontDisplay = this.newForm.isFrontDisplay ? 1 : 0
          if (this.newForm.id) { // id存在则是修改
            await update(this.newForm)
          } else { // id不存在则是新增
            await add(this.newForm)
          }
          this.$message.success(`${this.dialogTitle}成功!`)
          this.cancel()
          this.$emit('update')
        }
      })
    },
    // 取消
    cancel () {
      this.newForm = {
        subjectName: '',
        isFrontDisplay: true
      }
      this.$emit('update:showdialog', false)
    },
    // 根据id渲染修改弹窗
    async getDetail (id) {
      const { data } = await detail({ id })
      this.newForm = data
      this.newForm.isFrontDisplay = +data.isFrontDisplay === 1
    }
  }
}
</script>

<style scoped lang='less'></style>
